package cn.dm.server.use_token;


import com.dm.common.Constants;
import com.dm.common.MD5;
import com.dm.common.RedisUtils;
import com.dm.vo.DmUserVO;
import com.alibaba.fastjson.JSON;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private RedisUtils redisUtils;
    /**
     * 获取token字符串字符串
     *
     * @param user
     * @param agent
     * @return
     * @throws Exception
     */
    public String getToken(String agent, DmUserVO user) throws Exception {


       /*
        token:PC-3066014fa0b10792e4a762-23-20170531133947-4f6496
        前缀: token:
        终端类型: PC / MOBILE
        userCode信息(MD5混淆) : 32位
        userID:来自数据库
        Token创建时间: yyyMddHmmss
        最后6位根据User-Agent MD5混淆: 6位验证码
        */


        StringBuilder stringBuilder = new StringBuilder("token:"+agent+"-");
        //Personal computer ----->PC

        //追加根据用户编号生成32为MD5号码
        stringBuilder.append(MD5.getMd5(user.getPhone(), 32) + "-");

        //追加用户id
        stringBuilder.append(user.getUserId() + "-");

        //拼接当前时间段
        stringBuilder.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));

        //根据设备类型生成6为号码
        stringBuilder.append("-" + MD5.getMd5(agent, 6));

        return stringBuilder.toString();
    }


    /**
     * 保存token
     *
     * @param token
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public Boolean saveToken(String token, DmUserVO user) throws Exception {

        redisUtils.set(token, new Long(Constants.Redis_Expire.SESSION_TIMEOUT),JSON.toJSONString(user));
            return true;
    }

    /**
     * 保存key=id,value=token
     * @param id
     * @param token
     * @return
     * @throws Exception
     */
    public Boolean saveTokenById(String id, String token) throws Exception{
        redisUtils.set(id, new Long(Constants.Redis_Expire.SESSION_TIMEOUT),token);
        return true;
    }

    /**
     * 验证token是否存在
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public String validateToken(String id) throws Exception {

        Boolean tokenKey = null;

           tokenKey = redisUtils.exist(id);
           if(tokenKey){
               return  redisUtils.get(id).toString();
           }else{
               return null;
           }



    }

    /**
     * 删除token
     *
     * @param token
     * @throws Exception
     */
    public void deleteToken(String token) throws Exception{
        redisUtils.delete(token);


    }


}
